package org.example.timer.connectionpool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class PoolTest {
    public static void main(String[] args) {
        // 模拟10个线程，获取链接
        CustomDataSourcePool sourcePool = new CustomDataSourcePool();

        ExecutorService service = Executors.newFixedThreadPool(10);
        CountDownLatch latch = new CountDownLatch(20);
        for (int i = 0; i < 20; i++) {
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        log.info("获取到链接：" + sourcePool.getConnection());
                        // 业务处理时间200毫秒
                        Thread.sleep(200);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    latch.countDown();
                }
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("连接池可用数量：" + sourcePool.getPollingCount());
        log.info("主线程执行完毕");
    }
}
